#include "ServerSession.h"
#include <iostream>
#include <boost/asio.hpp>

using namespace ENE;

ServerSession::ServerSession(boost::asio::io_service& ioService, const unsigned short& port)
: m_io_service(ioService), m_acceptor(ioService,boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port))
{
}

void ServerSession::listen(ListenCallback handler)
{
	//ecoute les connection
	boost::shared_ptr<SocketConnection> connection(new SocketConnection(m_io_service));

	m_acceptor.async_accept(connection->socket(),
		boost::bind(&ServerSession::handleListen, this, boost::asio::placeholders::error, handler, connection));
}

void ServerSession::handleListen(const boost::system::error_code& error, ListenCallback handler, boost::shared_ptr<SocketConnection> connection)
{
	handler(error, connection);
}

void ServerSession::send(const std::string& data)
{
	for(std::map<int, boost::shared_ptr<SocketConnection> >::iterator i=m_clients.begin();
		i!=m_clients.end();i++)
	{
		m_io_service.post(boost::bind(&SocketConnection::write, i->second, data));
	}
}

void ServerSession::close()
{
	for(std::map<int, boost::shared_ptr<SocketConnection> >::iterator i=m_clients.begin();
		i!=m_clients.end();i++)
	{
		i->second.reset();
	}
}

void ServerSession::close(int key)
{
	std::map<int, boost::shared_ptr<SocketConnection> >::iterator clientit = m_clients.find(key);
	if(clientit!=m_clients.end())
		clientit->second.reset();
}

void ServerSession::addClient(int id, boost::shared_ptr<SocketConnection> client)
{
	m_clients[id] = client;
}


